import axios from 'axios'
import qs from 'qs'
import { BaseResult } from './types/BaseResult'
import { log } from './logger'

const BASE_URL = 'https://api.huhuiyu.top'
const TOKEN_KEY = '_token'

class LocalToken {
  static loadToken() {
    let token = localStorage.getItem(BASE_URL + TOKEN_KEY)
    return token ? token : ''
  }
  static saveToken(data: BaseResult) {
    if (data && data.token) {
      localStorage.setItem(BASE_URL + TOKEN_KEY, data.token)
    }
  }
  static removeToken() {
    localStorage.removeItem(BASE_URL + TOKEN_KEY)
  }
}

const api_ajax = axios.create({ baseURL: BASE_URL })
const api_ajax_file = axios.create({ baseURL: BASE_URL })

const MAX_FILE_SIZE = 5 * 1024 * 1024
const MAX_FILE_SIZE_MESSAGE = { code: 500, success: false, message: '上传文件大小不能超过' + MAX_FILE_SIZE / 1024 / 1024 + 'MB' }

class ApiService {
  static uploadEditorImage(file: File, cb: Function) {
    if (file.size > MAX_FILE_SIZE) {
      cb(MAX_FILE_SIZE_MESSAGE)
      return
    }
    // 处理参数
    let formdata = new FormData()
    formdata.append('file', file)
    // 处理请求类型
    let method = 'POST'
    let promise = api_ajax_file({
      url: BASE_URL + '/tools/editor/uploadimg',
      data: formdata,
      method: method,
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: LocalToken.loadToken(),
      },
    })
    promise
      .then((resp) => {
        log.debug('应答结果：', resp)
        LocalToken.saveToken(resp.data)
        cb(resp.data)
      })
      .catch((error) => {
        log.error(error)
        cb({ code: 500, success: false, message: '网站忙，请稍后重试' })
      })
  }
  static userlogo(id: number = -1) {
    return id == -1 ? BASE_URL + '/user/logo?request_token=' + LocalToken.loadToken() : BASE_URL + '/user/logo/' + id
  }

  static upload(url: string, param: any, file: File, cb: Function) {
    if (file.size > MAX_FILE_SIZE) {
      cb(MAX_FILE_SIZE_MESSAGE)
      return
    }
    // 处理参数
    let formdata = new FormData()
    formdata.append('file', file)
    for (let key in param) {
      formdata.append(key, param[key])
    }
    // 处理请求类型
    let method = 'POST'
    let promise = api_ajax_file({
      url: BASE_URL + url,
      data: formdata,
      method: method,
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: LocalToken.loadToken(),
      },
    })
    promise
      .then((resp) => {
        log.debug('应答结果：', resp)
        LocalToken.saveToken(resp.data)
        cb(resp.data)
      })
      .catch((error) => {
        log.error(error)
        cb({ code: 500, success: false, message: '网站忙，请稍后重试' })
      })
  }

  static ajax(url: string, param: any, cb: Function, method: 'GET' | 'POST' | 'DELETE' | 'PATCH' | 'PUT' = 'GET') {
    // get请求使用地址栏传递参数
    if (method.toUpperCase() === 'GET') {
      let reqdata = qs.stringify(param, { allowDots: true })
      url = `${url}?${reqdata}`
      param = ''
    }
    let promise = api_ajax({
      url: url,
      method: method,
      data: param,
      headers: {
        Authorization: LocalToken.loadToken(),
      },
    })
    log.debug('请求信息：', url, method, param, LocalToken.loadToken())
    promise
      .then((resp) => {
        log.debug('应答结果：', resp)
        LocalToken.saveToken(resp.data)
        cb(resp.data)
      })
      .catch((error) => {
        log.error(error)
        cb({ code: 500, success: false, message: '网站忙，请稍后重试' })
      })
  }
  static get(url: string, param: any, cb: Function) {
    ApiService.ajax(url, param, cb, 'GET')
  }
  static post(url: string, param: any, cb: Function) {
    ApiService.ajax(url, param, cb, 'POST')
  }
  static delete(url: string, param: any, cb: Function) {
    ApiService.ajax(url, param, cb, 'DELETE')
  }
  static put(url: string, param: any, cb: Function) {
    ApiService.ajax(url, param, cb, 'PUT')
  }
  static patch(url: string, param: any, cb: Function) {
    ApiService.ajax(url, param, cb, 'PATCH')
  }
}

export { ApiService, LocalToken, BASE_URL }
